// 导入数据库操作
const { sqlOne, sqlBatch } = require('../db/common')

// 导入工具
const utils = require('../utils/index')

const trie =  require('../utils/trie');

// 成功响应 onSuccess 失败响应 onError

// 获取文章下的评论
exports.getCommentReply = async (req, res) => {
    const { commentId, pageSize, pageNum, desc } = req.query;
    const startNum = (pageNum - 1) * pageSize;

    let orderBy = 'ASC'; // 默认排序方向为升序  
    if (desc === 'desc') {
        orderBy = 'DESC'; // 如果 desc 为 'desc'，则设置为降序  
    }

    const sql = `  
        SELECT 
            tr.id as replyId,
            tr.content,
            tr.createdAt, 
            tu.id as userId,  
            tu.username,  
            tu.avatar  
        FROM 
            t_reply as tr,
            t_user as tu
        where 
            tr.deletedAt is NULL and 
            tr.comm_id=? and 
            tr.from_uid=tu.id   
        ORDER BY   
            tr.createdAt ${orderBy}  
        LIMIT   
            ?, ?;`;

    const sqlTotal = `select count(id) as total from t_reply where comm_id = ? and deletedAt is NULL;`

    const results = await sqlBatch(sql + sqlTotal, [commentId, startNum, pageSize, commentId]);
    console.log(results[0]);
    const reply = results[0]
    const total = results[1][0]['total']
    res.onSuccess({ reply, total })
}


exports.commentReply = async (req, res) => {
    try {
        const { commentId, userId, content, } = req.body

        // 评论关键字屏蔽

        const trieContent = trie.filterSensitiveWords(content)

        const replyId = req.auth.id
        const date = new Date();
        const sql = `insert into t_reply (comm_id,reply_target_id,content,from_uid,createdAt)values(?,?,?,?,?);`
        const results = sqlOne(sql, [commentId, userId, trieContent, replyId, date])
        res.onSuccess()
    } catch (e) {
        res.onError(e)
    }
}

// 获取回复我的列表
exports.getReplyMy = async (req,res) => {
    try{
        const { pageSize, pageNum } = req.query;
        const startNum = (pageNum - 1) * pageSize;
        const user_id = req.auth.id
        const sql = `select r.*,tc.content as comm_content,tc.article_id from t_comment as tc,
        (select tu.id as user_id,tu.username,tr.id as reply_id,tr.content as reply_content,tr.createdAt,tr.comm_id,tu.avatar 
        from t_reply as tr,t_user as tu where tr.from_uid = tu.id and tr.reply_target_id = ? and tr.deletedAt is NULL  ORDER BY tr.createdAt desc limit ?,? ) as r
        where tc.id = r.comm_id`
        const results = await sqlOne(sql,[user_id,startNum,pageSize])
        const sqltotal = `select count(tr.id) as total from t_reply as tr,t_user as tu where tr.from_uid = tu.id and tr.reply_target_id = ? and tr.deletedAt is NULL`
        const [{total}] = await sqlOne(sqltotal,[user_id])
        res.onSuccess({data:results,total})
    }catch(e){
        res.onError(e)
    }
}